package com.franklin.java.linemarker.sql;

import com.franklin.java.action.sql.SqlActionGroup;
import com.intellij.codeInsight.daemon.LineMarkerInfo;
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.event.DocumentListener;
import com.intellij.openapi.editor.markup.GutterIconRenderer;
import com.intellij.pom.Navigatable;
import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.Collection;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Franklin
 * @since 2021/9/6 19:58
 */
class SelectSqlLineMarkerInfo extends LineMarkerInfo<PsiElement> {

    protected PsiElement element;

    protected SqlActionGroup sqlActionGroup;

    SelectSqlLineMarkerInfo(
        @NotNull PsiElement element,
        @NotNull Icon icon,
        Navigatable navigatable,
        Collection<String> fixTargets
    ) {
        super(element, element.getTextRange(),
            icon, xmlTag -> "Fix map column names you had changed",
            (mouseEvent, xmlTag) -> {

            },
            GutterIconRenderer.Alignment.CENTER,
            () -> String.join(",", fixTargets)
        );
        this.element = element;
        this.sqlActionGroup = new SqlActionGroup(element);
        Optional.ofNullable(this.element.getContainingFile().getViewProvider().getDocument())
            .ifPresent(document -> document.addDocumentListener(new DocumentListener() {
                @Override
                public void beforeDocumentChange(@NotNull DocumentEvent event) {
                    sqlActionGroup.storeOldSqlResult();
                }
            }));
    }

    @Override
    public GutterIconRenderer createGutterRenderer() {
        return new LineMarkerGutterIconRenderer<>(this) {

            public AnAction getClickAction() {
                //点击编辑区域时缓存
                sqlActionGroup.storeOldSqlResult();
                return null;
            }

            public boolean isNavigateAction() {
                return true;
            }

            @Override
            public @Nullable
            ActionGroup getPopupMenuActions() {
                return sqlActionGroup;
            }

        };
    }

}
